//
//  Utilties.m
//  mendianjieke
//
//  Created by 响当当 on 7/30/19.
//  Copyright © 2019 dongzheng. All rights reserved.
//

#import "Utilties.h"
#include <arpa/inet.h>
#include <netdb.h>
#include <net/if.h>
#include <ifaddrs.h>
#import <dlfcn.h>
#import "CXAlertView.h"


@implementation Utilties
+ (void)monitorNetworking
{
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                [Utilties showAlertWithTitle:@"提示" content:@"暂无识别开启网络，是否前往设置" buttonTitle:@"确定" ConfirmWithBlock:^{
                    [Utilties openUrlSchedule:UIApplicationOpenSettingsURLString];
                }];
                break;
            case AFNetworkReachabilityStatusNotReachable:
                [Utilties showAlertWithTitle:@"提示" content:@"暂无识别开启网络，是否前往设置" buttonTitle:@"确定" ConfirmWithBlock:^{
                    [Utilties openUrlSchedule:UIApplicationOpenSettingsURLString];
                }];
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
            {
                NSLog(@"GPRS网络");
            }
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
            {
                NSLog(@"wifi网络");
            }
                break;
            default:
                break;
        }
        
    }];
}

/**
 * 获取当前屏幕显示的viewcontroller
 */
+ (UIViewController *)getCurrentVC
{
    //获得当前活动窗口的根视图
    UIViewController* vc = [UIApplication sharedApplication].keyWindow.rootViewController;
    while (1)
    {
        //根据不同的页面切换方式，逐步取得最上层的viewController
        if ([vc isKindOfClass:[UITabBarController class]]) {
            vc = ((UITabBarController*)vc).selectedViewController;
        }
        if ([vc isKindOfClass:[UINavigationController class]]) {
            vc = ((UINavigationController*)vc).visibleViewController;
        }
        if (vc.presentedViewController) {
            vc = vc.presentedViewController;
        }else{
            break;
        }
    }
    return vc;
}

/**
 *    url跳转
 */
+ (void)openUrlSchedule:(NSString *)urlStr
{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
}

//创建label
+ (UILabel *)creatLabelWithFrame:(CGRect)Rect
                    textAligment:(NSTextAlignment)textAligment
                        textClor:(UIColor *)color
                        textFont:(CGFloat)size
{
    UILabel *label = [[UILabel alloc]initWithFrame:Rect];
    label.textAlignment = textAligment;
    label.textColor = color;
    label.font = [UIFont systemFontOfSize:size];
    return label;
}

//创建button
+ (UIButton *)creatButtonWithFrame:(CGRect)Rect
                      textAligment:(UIControlContentHorizontalAlignment)textAligment
                              text:(NSString *)title
                          textClor:(UIColor *)color
                         buttonBGC:(UIColor *)bgcColor
                          textFont:(CGFloat)size
                            target:(id)vc
                            method:(SEL)method
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = Rect;
    [button setTitleColor:color forState:UIControlStateNormal];
    [button setTitle:title forState:UIControlStateNormal];
    [button.titleLabel setFont:[UIFont systemFontOfSize:size]];
    [button setContentHorizontalAlignment:textAligment];
    [button setBackgroundColor:bgcColor];
    [button addTarget:vc action:method forControlEvents:UIControlEventTouchUpInside];
    return button;
}

//电话号码
+ (BOOL)checkTel:(NSString *)mobileNumbel

{
    if (!mobileNumbel)
    {
        [SVProgressHUD showErrorWithStatus:@"请输入手机号码"];
        
        DISMISS_SVP(1.2f);
        
        return NO;
        
    }else{
        
        if (mobileNumbel.length == 11) {
            
            return true;
        }
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号码"];
        DISMISS_SVP(1.2f);
        return false;
    }
}


//这个函数就是将字典封装成转义的JSON字符串
+ (NSString *)toJSONString:(NSDictionary *)dict
{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *str = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    return str;
}

+ (void)showAlertWithTitle:(NSString *)titleStr
                   content:(NSString *)eventStr
               buttonTitle:(NSString *)btnTitle
            cancelBtnTitle:(NSString *)cancelBtnTitle
          ConfirmWithBlock:(void(^)(void))comfirm
{
    
    CXAlertView *alterview = [[CXAlertView alloc]initWithTitle:titleStr message:eventStr cancelButtonTitle:cancelBtnTitle];
    
    [alterview addButtonWithTitle:btnTitle type:CXAlertViewButtonTypeDefault handler:^(CXAlertView *alertView, CXAlertButtonItem *button) {
        [alertView dismiss];
        
        comfirm();
        
    }];
    [alterview show];
}

/*
 ** 提示操作,不含取消
 
 */
+ (void)showAlertWithTitle:(NSString *)titleStr
                   content:(NSString *)eventStr
               buttonTitle:(NSString *)btnTitle
          ConfirmWithBlock:(void(^)(void))comfirm
{
    
    CXAlertView *alterview = [[CXAlertView alloc]initWithTitle:titleStr message:eventStr cancelButtonTitle:nil];
    [alterview addButtonWithTitle:btnTitle type:CXAlertViewButtonTypeDefault handler:^(CXAlertView *alertView, CXAlertButtonItem *button) {
        [alertView dismiss];
        comfirm();
    }];
    [alterview show];
}

//时间戳转换成时间
+ (NSString *)getTime:(NSString *)time
{
    NSTimeInterval interval = [time doubleValue] / 1000.0;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateString = [formatter stringFromDate: date];
    
    return dateString;
}


//获取当前年月
+ (NSString *)getYearAndMonth
{
    NSDate *date =[NSDate date];//简书 FlyElephant
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    
    [formatter setDateFormat:@"yyyy"];
    NSInteger currentYear=[[formatter stringFromDate:date] integerValue];
    [formatter setDateFormat:@"MM"];
    NSInteger currentMonth=[[formatter stringFromDate:date]integerValue];
    [formatter setDateFormat:@"dd"];
    NSInteger currentDay=[[formatter stringFromDate:date] integerValue];
    
    return [NSString stringWithFormat:@"%ld-%ld-%ld",currentYear,currentMonth,currentDay];
    
}


//字典转JSON
+(NSString *)convertJSONWithDic:(NSDictionary *)dic
{
    NSError *err;
    NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&err];
    if (err) {
        return @"字典转JSON出错";
    }
    return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}

//JSON转字典
+(NSDictionary *)convertDicWithJSON:(NSString *)jsonStr
{
    if (jsonStr.length == 0) {
        return nil;
    }
    NSError *err;
    NSData *jsondata = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsondata options:NSJSONReadingMutableContainers error:&err];
    if (err) {
        return nil;
    }
    
    return dic;
}
@end
